package com.taxicall.taxi;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import taxicall.entities.NetworkMessage;
import taxicall.entities.NetworkMessage.MessageType;
import taxicall.entities.Taxi;
import taxicall.entities.TaxiLocation;
import udptransport.SerializationUtils;
import udptransport.UdpNetworkService;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TaxiIntro extends TaxiNetworkActivity {
	
	private Button enterButton;
	private EditText ipText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_taxi_intro);
		
		ipText = (EditText)findViewById(R.id.ipText);
		enterButton =(Button) findViewById(R.id.introBut);
		
		enterButton.setClickable(bound);
		enterButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				enterButton.setClickable(false);
				
				new Thread(new Runnable() {
					@Override
					public void run() {
						if(!bound) {
							Toast.makeText(getApplicationContext(), "NetworkService is not bound please try again later", Toast.LENGTH_LONG).show();
							return;
						}
						
						enterButton.setText("Connecting...");
						
						onEnterButtonClick();
						
						enterButton.setClickable(true);
						enterButton.setText("Enter");
					}
				}).start();
			}
		});
	}
	
	private void onEnterButtonClick(){
		String ipInput = ipText.getText().toString();
		try{
			serverIp = InetAddress.getByName(ipInput);
		}
		catch(UnknownHostException e){
			Toast.makeText(getApplicationContext(), "Please insert a valid ip", Toast.LENGTH_LONG).show();
			return;
		}
		
		// open the socket
		if (network == null) {
			try {
				network = service.open();
			} catch (SocketException e) {
				showSimpleDialog("Network error",
						"Couldn't create the network socket.");
				e.printStackTrace();
			}
		}
		
		if(network != null){
			TaxiLocation location = new TaxiLocation("Omonoia", "Plateia Omonoias", 37.983742, 23.727965);
			Taxi newTaxi = Taxi.createWithoutId(serverIp, location);
			
			// send a "join" message to the server
			NetworkMessage msg = new NetworkMessage(MessageType.UpdateTaxi, newTaxi);
			try {
				network.send(msg, serverIp, UdpNetworkService.DEFAULT_PORT);
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(getApplicationContext(), "Couldnt send message to server, please try again.", Toast.LENGTH_LONG).show();
				return;
			}
			
			// wait for reply
			DatagramPacket response;
			try {
				response = network.receive(120000);
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(getApplicationContext(), "Couldnt receive message from server, please try again.", Toast.LENGTH_LONG).show();
				return;
			}
			
			// if response is null, timeout was hit or the network is down..prompt the user to try again 
			if(response == null){
				Toast.makeText(getApplicationContext(), "Couldnt receive message from server, please try again.", Toast.LENGTH_LONG).show();
				return;
			}
			else{
				// if reply ok, continue to next activity
				NetworkMessage serverMsg = (NetworkMessage) SerializationUtils.deserialize(response.getData());
				thisTaxi = (Taxi) serverMsg.getDataObject();
				
				startNextActivity();
			}
		}
	}
	
	private void showSimpleDialog(String title, String message){
		AlertDialog.Builder dialog = new Builder(getApplicationContext());
		dialog.setCancelable(false);
		dialog.setTitle(title);
		dialog.setMessage(message);
		dialog.setPositiveButton("Ok", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				TaxiIntro.this.finish();
			}
		});
		dialog.create();
		dialog.show();
	}
	
	private void startNextActivity() {
		assert(thisTaxi != null && thisTaxi.getId() != 0 && serverIp != null);
		Intent intent = new Intent(getApplicationContext(),
				PassengerApproval.class);
		intent.putExtra("thisTaxi", thisTaxi);
		intent.putExtra("serverIp", serverIp);
		startActivity(intent);
	}
}
